package com.jzz.eletuanbackend.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jzz.eletuanbackend.entity.Block;
import com.jzz.eletuanbackend.entity.Commodity;
import com.jzz.eletuanbackend.entity.Order;
import com.jzz.eletuanbackend.entity.Shop;
import com.jzz.eletuanbackend.mapper.BusinessMapper;
import com.jzz.eletuanbackend.mapper.OrderMapper;
import com.jzz.eletuanbackend.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BusinessService {

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private OrderMapper orderMapper;

    public Msg listShops(Long userId) {
        return Msg.ok(businessMapper.listShops(userId));
    }

    public Msg newShop(
            Long userId,
            String contact,
            String name,
            String description,
            String displayLocation,
            Double lng,
            Double lat,
            String licenseId,
            Double startPrice,
            Double shipPrice
    ) {
        try {
            Integer result = businessMapper
                    .newShop(userId, contact, name, description, displayLocation, lng, lat, licenseId, startPrice, shipPrice);
            if (result > 0) {
                return Msg.ok("添加成功");
            } else {
                return Msg.err(-1, "添加失败");
            }
        } catch (Exception e) {
            return Msg.err(-1, e.getMessage());
        }
    }

    public Msg closeShop(Long shopId) {
        try {
            Integer result = businessMapper.closeShop(shopId);
            if (result == 0) {
                return Msg.ok("还有未处理完的订单，无法打烊");
            } else {
                return Msg.ok("店铺打烊");
            }
        } catch (Exception e) {
            return Msg.err(-1, e.getMessage());
        }
    }

    public Msg openShop(Long shopId) {
        try {
            businessMapper.openShop(shopId);
            return Msg.ok("店铺营业");
        } catch (Exception e) {
            return Msg.err(-1, e.getMessage());
        }
    }

    public Msg unregisterShop(Long shopId) {
        try {
            businessMapper.unregisterShop(shopId);
            return Msg.ok("店铺已注销");
        } catch (Exception e) {
            return Msg.err(-1, e.getMessage());
        }
    }

    public Msg editShop(Long id,
                        Double startPrice,
                        Double shipPrice,
                        String desc) {
        try {
            businessMapper.editShop(id, startPrice, shipPrice, desc);
            return Msg.ok("修改成功");
        } catch (Exception e) {
            return Msg.err(-1, e.getMessage());
        }
    }

    public Msg getShop(Long id) {
        return customerService.shop(id);
    }

    @Transactional
    public Msg blockAdd(Long shopId, String name) {
        Block block = new Block();
        block.setName(name);
        if (businessMapper.existsBlockName(name, shopId) == 0) {
            if (businessMapper.addBlock(block) > 0) {
                if (businessMapper.addBlockToShop(block.getId(), shopId) > 0) {
                    return Msg.ok("添加成功");
                }
            }
        } else {
            return Msg.err(-1, "不允许重复的板块名称");
        }

        return Msg.err(-1, "添加失败");
    }

    @Transactional
    public Msg blockRemove(Long blockId) {
        if (businessMapper.removeBlockFromShop(blockId) > 0) {
            return Msg.ok("删除成功");
        }
        return Msg.err(-1, "删除失败");
    }

    @Transactional
    public Msg itemAdd(Long blockId, String name, String image, String description,
                       String specifications, Double price, Integer minQuantity, Double packPrice) {
        /* specifications: [ { name: "选规格", spec: { "微辣": 0.0, "不辣": 0.0, "加孜然": 0.5 } } ] */
        Commodity commodity = new Commodity(name, image, description, specifications, price, minQuantity, packPrice);
        // Check specs
        JSONArray specs = JSON.parseArray(specifications);
        if (specs.size() > 0) {
            commodity.setMinQuantity(1);
        } else {
            if (minQuantity < 1) {
                commodity.setMinQuantity(1);
            }
        }

        if (businessMapper.newItem(commodity) > 0) {
            if (businessMapper.addItemToShop(blockId, commodity.getId()) > 0) {
                return Msg.ok("添加成功");
            }
        }
        return Msg.err(-1, "添加失败");
    }

    @Transactional
    public Msg itemEdit(Long id, Long blockId, String name, String image, String description,
                        String specifications, Double price, Integer minQuantity, Double packPrice) {
        Commodity commodity = new Commodity(id, name, image, description, specifications, price, minQuantity, packPrice);
        JSONArray specs = JSON.parseArray(specifications);
        if (specs.size() > 0) {
            commodity.setMinQuantity(1);
        } else {
            if (minQuantity < 1) {
                commodity.setMinQuantity(1);
            }
        }

        if (businessMapper.editItem(commodity) > 0 &&
                businessMapper.changeItemBlock(id, blockId) > 0) {
            return Msg.ok("修改成功");
        } else {
            return Msg.err(-1, "修改失败");
        }
    }

    @Transactional
    public Msg itemRemove(Long id) {
        if (businessMapper.removeItem(id) > 0) {
            return Msg.ok("删除成功");
        }
        return Msg.err(-1, "删除失败");
    }

    public Msg itemGet(Long id) {
        Commodity commodity = businessMapper.getCommodity(id);
        return Msg.ok(commodity);
    }

    @Transactional
    public Msg acceptOrder(Long orderId) {
        if (orderMapper.isOrderCanceled(orderId) == 0) {
            orderMapper.acceptOrder(orderId, System.currentTimeMillis());
            return Msg.ok("已确认订单，请尽快出餐");
        } else {
            return Msg.err(-1, "订单已被取消");
        }
    }

    public Msg getOrder(Long id) {
        return customerService.getOrder(id);
    }

    public Msg getAllOrders(Long userId) {
        List<Long> allShopIds = businessMapper.allShopIds(userId);

        JSONArray result = new JSONArray();

        allShopIds.forEach(shopId -> {
            result.add(getShopOrders(shopId).getData());
        });

        return Msg.ok("success", result);
    }

    public Msg getShopOrders(Long shopId) {
        JSONObject shop = new JSONObject();
        Shop s = businessMapper.getShop(shopId);
        shop.put("shopId", shopId);
        shop.put("shopName", s.getName());

        List<Order> orders = orderMapper.getByShopId(shopId);
        shop.put("orders", orders);

        return Msg.ok(shop);
    }

}
